/**
 * @author Dave
 */
cmx.dialog.LoginDialog = Ext.extend(Ext.Window, {
	initComponent : function(){
		cmx.dialog.LoginDialog.superclass.initComponent.call(this);
		
		this.loginForm = new cmx.panel.LoginFormPanel({
			labelWidth: 75,
			border: false,
			bodyStyle:'background:transparent;padding:5px 5px 0',
			width: 350,
        	defaults: {width: 230}
		});
		this.add(this.loginForm);
		
		this.loginButton = {
			xtype: 'button',
			text: 'Login',
			handler: this.onLoginClick,
			scope: this
		};
		this.addButton(this.loginButton);
	},
	
	onLoginClick : function(){
		var form = this.loginForm;
		
		if (this.isFormValid()) {
			Ext.Ajax.request({
			   	url: this.authUrl,
			   	callback: this.onLoginServiceResponse,
			   	scope: this,
			   	jsonData: {
					username: form.usernameField.getValue(),
					password: form.passwordField.getValue()
				}
			});
		} else {
			Ext.Msg.show({
				title: 'Login failed',
				msg: 'Sorry but we were unable to log you in. <br />Reason: You must provide both a user name and password.',
				buttons: Ext.MessageBox.OK,
				icon: Ext.MessageBox.WARNING
			});
		}				
	},
	
	onLoginServiceResponse : function(options, success, response){
		// decode the response
		var login = Ext.util.JSON.decode(response.responseText);
		
		if (success && login.success) {
			var loginForm = Ext.get('loginForm').dom;
			var tokenField = Ext.get('token').dom;
			
			tokenField.value = login.token;
			loginForm.submit();
		} else {
			Ext.Msg.show({
				title: 'Login failed',
				msg: 'Sorry but we were unable to log you in. <br />Reason: ' + login.msg,
				buttons: Ext.MessageBox.OK,
				icon: Ext.MessageBox.ERROR
			});
		}
	},
	
	isFormValid : function(){
		var form = this.loginForm;
		
		if (form.usernameField.isValid() && form.passwordField.isValid()) {
			return true;
		}
		
		return false;	
	},
	
	show : function(){
		cmx.dialog.LoginDialog.superclass.show.apply(this, arguments);
		this.center() ;
		this.loginForm.usernameField.focus(true, true);
	}
	
});
